--
-- Author: mm
-- Date: 2018-08-09 10:28:39
--
-- NewerbattleguideController
--

local NewerbattleguideView = import("..views.NewerbattleguideView")
local NewerbattleguideRoleView = import("..views.NewerbattleguideRoleView")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)

local guideType =
{
    PauseGuide = 1, -- 暂停类型引导，通过对单位释放眩晕实现
    StopGuide = 2, -- 停止类型引导，通过停止战斗引擎实现
    OrderGuide = 3, -- 剧情（顺序）引导
    GuideEnd = 4 -- 引导结束
}

function ClassRef:ctor(data)
    self.super.ctor(self, data)
end

function ClassRef:init()
    self._model = app:getInst("NewerbattleguideModel")
    self._nextGuideIdx = 1 -- 指向下一步引导位于配置中的位置
    self:_parseGuideConfs()
end

-- 解析引导步骤配置
function ClassRef:_parseGuideConfs()
    self._allGuideConfs = {}

    local guideRoles = self._model:getGuideRoles()
    local classId
    self._confs = guideRoles
    for _, v in ipairs(guideRoles) do
        classId = v:getClassID()
        self._allGuideConfs[classId] = GD:getNewerBattleGuideConfsByClass(classId)
    end
end

function ClassRef:listEvent()
    return {}
end

function ClassRef:removeListeners()
    self.super.removeListeners(self)
end

function ClassRef:openView(data)
    self._selectedRole = data or self._confs[1]
    if cc.isDead(self._view) then
        self._view = NewerbattleguideView.new()
        self._view:onCloseView(handler(self, self.closeView))
        self._view:onClearView(handler(self, self.clearView))
        self._view:onOperate(handler(self, self.onOperate))
        self:addChild(self._view)
    end
    self._guideConfs = self._allGuideConfs[tonumber( data:getClassID())]
    self._view:playCameraZoomAction()
    self._view:show()
end

function ClassRef:clearView()
    if self._view then
        self._view = nil
    end
end

function ClassRef:getNextGuideIndex()
    return self._nextGuideIdx
end

-------------------------------------------------------
-- 对外接口：告知触发了新手战
function ClassRef:triggerNewerBattle()
    EM:notify("OnGuideBattleAdEvent", Enums.GuideBattleAdEvent.BattleStart)
    BattleManager:SimulateBattle(self._selectedRole:getClassID())
    self._view:triggerNewerBattle()
end

-- 对外接口：查询新手战引导是否结束
function ClassRef:isNewerBattleGuideEnded()
    local isBattleGuideEnd = app:isBattleGuideComp()
    if isBattleGuideEnd then
        return true
    else
        return self._guideConfs and self._nextGuideIdx > #self._guideConfs or false
    end
end

-- 对外接口：根据战斗状态判断是否触发当前引导
-- 参数列表：技能Id，技能状态
function ClassRef:triggerBattleGuideEvent(skillId, skillStage)
    if not self._guideConfs then
        return
    end
    local curGuideConf = self._guideConfs[ self._nextGuideIdx ]
    if skillId == tonumber(curGuideConf.endSkillId) and skillStage == "on-hit" then
        print(" ===============>>>>>> 战斗事件结束引导", self._nextGuideIdx, skillId, skillStage) --@ignore
        self._view:nodeReturn()
        self:onOperate("curGuideEnd")
    end
    -- 防止当前引导变更
    local curGuideConf = self._guideConfs[self._nextGuideIdx]
    if curGuideConf.triggerPoint and
        skillStage == curGuideConf.triggerPoint then -- 触发阶段一致？
        if curGuideConf.triggerSkillId and
            skillId == tonumber(curGuideConf.triggerSkillId) then -- 触发技能id一致?
            print(" ===============>>>>>> 战斗事件触发引导 ", self._nextGuideIdx, skillId, skillStage)--@ignore
            local delayTime = (tonumber( curGuideConf.triggerOffset or 0)) / 1000
            scheduler.newCron(function()
                self:triggerBattleGuide()
            end, delayTime)
        end
    end
end

-- 对外接口：触发战斗中引导
function ClassRef:triggerBattleGuide()
    print(" ==================>>>>>> 触发引导 triggerBattleGuide", self._nextGuideIdx)--@ignore
    if self._guideStart then
        print(" ==================>>>>>> 当前引导正在进行 ")--@ignore
        return
    end
    if self._nextGuideIdx == 3 then
        EM:notify("OnGuideBattleAdEvent", Enums.GuideBattleAdEvent.RoleMove)
    end
    self._guideStart = true

    local curGuideConf = self._guideConfs[ self._nextGuideIdx ]

    if guideType.StopGuide == tonumber(curGuideConf.guideType) then -- 停止类型引导?
        -- 需要外部停止战斗引擎
        print( " ---------------->>>>>>>> 引擎暂停" )
        BattleManager:pauseBattle(true)
    elseif guideType.GuideEnd == tonumber(curGuideConf.guideType) then -- 引导结束?
        -- boss死亡特效外放
        self._view:playGuideEndAni()
        return
    end
    self._view:refresh(curGuideConf)
end

local dataTemp = {skill = 49999001 }
-- 当前引导步骤进行中
function ClassRef:_curGuideGoing()
    if self._guideOnGoing then return end
    self._guideOnGoing = true
    local curGuideConf = self._guideConfs[self._nextGuideIdx]
    local guideTypeTemp = tonumber(curGuideConf.guideType)
    if guideType.PauseGuide == guideTypeTemp then -- 当前是暂停类型引导？
        -- 后台释放群体净化
        print(" ---------------->>>>>>>> 群体净化")
        if BattleManager.mBattleController then
            BattleManager.mBattleController.model:onInput(dataTemp, Enums.CmdID.Cmd_Skill, Enums.TargetType.TargetType_Id)
        end
    elseif guideType.StopGuide == guideTypeTemp then -- 当前是停止类型引导？
        -- 继续战斗引擎
        print(" ---------------->>>>>>>> 引擎继续")
        BattleManager:resumeBattle(true)
    end
end

-- 当前引导步骤完成
function ClassRef:_curGuideComplete()
    if self._nextGuideIdx + 1 > #self._guideConfs then
        print(" ---------------->>>>>>>> 整个战斗引导结束")
        app:dispatchCustomEvent(Constant.BattleNewerGuideEndFlag)
    end

    -- 新手战埋点
    if self._nextGuideIdx == 4 then
        -- skill 1
        EM:notify("OnGuideBattleAdEvent", Enums.GuideBattleAdEvent.Skill1)
    elseif self._nextGuideIdx == 6 then
        -- attack
        
    elseif self._nextGuideIdx == 12 then
        -- skill 2
        EM:notify("OnGuideBattleAdEvent", Enums.GuideBattleAdEvent.Skill2)
    elseif self._nextGuideIdx == 17 then
        -- skill 3
        EM:notify("OnGuideBattleAdEvent", Enums.GuideBattleAdEvent.Skill3)
    elseif self._nextGuideIdx == 18 then
        -- skill 4
        EM:notify("OnGuideBattleAdEvent", Enums.GuideBattleAdEvent.Skill4)
    end

    -- 开始处理下一步
    self._nextGuideIdx = self._nextGuideIdx + 1
    local nextGuideConf = self._guideConfs[self._nextGuideIdx]
    if not nextGuideConf then -- 下一步引导步骤不存在？
        -- 整个引导结束
        print( " ---------------->>>>>>>> 整个引导结束" )
        self:closeView()
        -- 打开登录UI
        app:openLoginView(self._selectedRole:getId())
        return
    end
    if guideType.OrderGuide == tonumber(nextGuideConf.guideType) then -- 下一步剧情引导？
        self:triggerBattleGuide() -- 直接触发下一步引导
    end
end

function ClassRef:getMapPositionTriggerBattle()
    if self._selectedRole then
        return self._selectedRole:getMapPositionTriggerBattle()
    end
end



---------------------------------------->>>>>>>>> 以下：新手战引导选角UI <<<<<<<<<----------------------------------------

local tipsPrefix = "newerBattleDialog"

function ClassRef:beginBattleGuide()
    UIHandler:blackScreenFade("fadeIn",0)
    local exitCall = function()
        self:openSelectedRoleView()
    end
    local params =
    {

        nextTime = 2.7,
        fontSize = 24,
        delayTime = 0,
        fadeTime = 0.5,
        stayTime = 1.2,
        lineWidth = display.width,
        overDelayTime = 0.8,
        color = cc.c4b(255,255,255,255),
    }
    local function callBackFinal()
        UIHandler:fadeWordsViewVisibility(false)
        UIHandler:blackScreenFade("fadeOut",0,nil,exitCall)
        UIHandler:showBlackScreenFadeout(1)
    end
    local function callBackNextTip2()
        params.words = L(tipsPrefix..3)
        params.callback = callBackFinal
        UIHandler:fadeWordsViewVisibility(false)
        UIHandler:fadeWordsViewVisibility(true, params)
    end
    local function callBackNextTip1()
        params.words = L(tipsPrefix..2)
        params.callback = callBackNextTip2
        UIHandler:fadeWordsViewVisibility(false)
        UIHandler:fadeWordsViewVisibility(true, params)
    end
    params.words = L(tipsPrefix..1)
    params.callback = callBackNextTip1
    UIHandler:fadeWordsViewVisibility(true, params)
end

function ClassRef:openSelectedRoleView()
    if nil == self._selecedRoleView then
        self._selecedRoleView = NewerbattleguideRoleView.new(nil, self._confs)
        self._selecedRoleView:onCloseView(function()
            self._selecedRoleView:removeFromParent(true)
        end )
        self._selecedRoleView:onClearView(handler(self, self.clearSelecedRoleView))
        self._selecedRoleView:onOperate(handler(self, self.onOperate))
        self:addChild(self._selecedRoleView)
    end
    self._selecedRoleView:show()
end

function ClassRef:clearSelecedRoleView()
    if self._selecedRoleView then
        self._selecedRoleView = nil
    end
end
--------------------------------------------------------------------------------------------------------------------------




-------------------------------------------------------
function ClassRef:onOperate(op, data)
    print(" ==========>>>> NewerbattleguideController:onOperate op = " .. op)

    if op == "selectedRoleStart" then -- 选角开始
        -- 修改地图角色形象，默认是1的形象，不需要修改
        if data > 1 then
            local roles = self._model:getGuideRoles()
            local baseInfo = roles[data]:getBaseInfo()
            FieldManager:updateMyCharacterUserBaseInfo(baseInfo)
        end
        GemService:SetEvent(10, true, tostring(data), false, false)
    elseif op == "selectedRoleEnd" then -- 选角完成
        -- 正式引导测试
        self._nextGuideIdx = 1
        EM:notify("OnGuideBattleAdEvent", Enums.GuideBattleAdEvent.IntroChoose)
        self:openView(data)
    elseif op == "curGuideGoing" then
        self:_curGuideGoing()
    elseif op == "curGuideEnd" then -- 当前步骤完成？
        self._guideStart = false
        self._guideOnGoing = false
        self._view:curGuideEndClear()
        self:_curGuideComplete()
    elseif op == "cameraActionEnd" then -- 开场镜头动作完成
        self:triggerBattleGuide() -- 开始第一步
    elseif op == "curGuideEndAndtriggerBattleGuide" then
        self._guideStart = false
        self._guideOnGoing = false
        self._view:curGuideEndClear()
        self:_curGuideComplete()
        local curGuideConf = self._guideConfs[self._nextGuideIdx]
        local delayTime = (tonumber(curGuideConf.triggerOffset or 0)) / 1000
        scheduler.newCron(function()
            self:triggerBattleGuide()
        end, delayTime)
    elseif op == "skipGuide" then
        self._guideStart = false
        self._guideOnGoing = false
        self:_curGuideGoing()
        self._view:nodeReturn()
        self._view:curGuideEndClear()
        app:dispatchCustomEvent(Constant.BattleNewerGuideEndFlag)
        self:closeView()
        -- 打开登录UI
        app:openLoginView(self._selectedRole:getId())
    end
end

return ClassRef
